package com.hoshiibuy.purchase.service.impl;

import com.hoshiibuy.common.exception.ServiceException;
import com.hoshiibuy.common.rpc.Response;
import com.hoshiibuy.common.utils.GenerationCode;
import com.hoshiibuy.purchase.entity.Po;
import com.hoshiibuy.purchase.entity.Podetail;
import com.hoshiibuy.purchase.service.PoService;
import com.hoshiibuy.purchase.service.PodetailService;
import com.hoshiibuy.purchase.service.PurchaseService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.List;

import static com.hoshiibuy.common.utils.GenerationCode.getCount;

/**
 * @Author:campchen
 * @Date:Created in 下午 04:43 2019/5/16
 * @PACKAGENAME com.hoshiibuy.purchase.service
 * @Description
 */
@Slf4j
@Service
public class PurchaseServiceImpl implements PurchaseService {
    @Autowired
    private PoService poService;
    @Autowired
    private PodetailService podetailService;

    //采购单--销售订单自动生成--9  备货单--采购人员采购--2
    @Transactional(rollbackFor = Exception.class)
    @CacheEvict(cacheNames = "Po", allEntries = true)
    @Override
    public boolean saveActualPurchase(String code,Po poParam, List<Podetail> list) {
        boolean flag=false;
        DateTimeFormatter df = DateTimeFormatter.ofPattern("yyMMdd-HH-mm-ss");
        LocalDateTime time = LocalDateTime.now();
        String localTime = df.format(time);
        String poCode="0001";
        if(localTime==code){
            int count=GenerationCode.getCount();
           if (count<10){
               poCode="000"+count;
           }else if (count<100){
               poCode="00"+count;
           }else if (count<1000){
               poCode="0"+count;
           }else {
               poCode=count+"";
           }
        }
        try{
            poParam.setPoNo(code+poCode+poParam.getType());
            flag= poService.save(poParam);
            if (!flag){
                throw new ServiceException("新采购单异常");
            }
            for (Podetail p : list) {
                p.setPoid(poParam.getId());
                flag = podetailService.save(p);
                if (!flag) {
                    throw new ServiceException("新增采购详情异常");
                }
            }
        }catch (Exception e){
            log.error("新增异常", e);
        }
        return flag;
    }

}
